<template>
  <div class="dashboard-container">
    <el-card class="page-card">
      <template #header>
        <div class="page-header">
          <span>系统概览</span>
        </div>
      </template>
      
      <!-- 统计卡片区域 -->
      <div class="stats-grid">
        <el-card class="stat-card success">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon class="icon-large"><VideoCamera /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ cameraCount }}</div>
              <div class="stat-label">在线摄像头</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card warning">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon class="icon-large"><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ alertCount }}</div>
              <div class="stat-label">未处理告警</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card primary">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon class="icon-large"><Van /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ vehicleCount }}</div>
              <div class="stat-label">今日检测车辆</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card danger">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon class="icon-large"><CloseBold /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ violationCount }}</div>
              <div class="stat-label">今日违规次数</div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 图表区域 -->
      <div class="charts-grid">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>最近24小时告警趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-skeleton :rows="1" animated />
            </div>
            <div v-else class="chart-content" ref="alertTrendChart"></div>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>违规类型分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-skeleton :rows="1" animated />
            </div>
            <div v-else class="chart-content" ref="violationTypeChart"></div>
          </div>
        </el-card>
      </div>
      
      <!-- 最近告警列表 -->
      <el-card class="alerts-card">
        <template #header>
          <div class="card-header">
            <span>最近告警</span>
            <el-button type="text" @click="$router.push('/alerts')">查看全部</el-button>
          </div>
        </template>
        <el-table :data="recentAlerts" style="width: 100%">
          <el-table-column prop="id" label="告警ID" width="80" />
          <el-table-column prop="camera_name" label="摄像头" width="150" />
          <el-table-column prop="violation_type" label="违规类型" />
          <el-table-column prop="timestamp" label="告警时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="viewAlertDetail(row.id)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {
  VideoCamera, 
  Warning, 
  Van, 
  CloseBold 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { api } from '../api/apiService'

export default {
  name: 'Dashboard',
  components: {
    VideoCamera,
    Warning,
    Van,
    CloseBold
  },
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const cameraCount = ref(0)
    const alertCount = ref(0)
    const vehicleCount = ref(0)
    const violationCount = ref(0)
    const recentAlerts = ref([])
    const alertTrendChart = ref(null)
    const violationTypeChart = ref(null)
    
    // 图表实例
    let alertTrendInstance = null
    let violationTypeInstance = null
    
    // 初始化数据
    const initializeData = async () => {
      try {
        loading.value = true
        
        // 获取系统统计数据
        const stats = await api.system.getStatistics()
        
        // 设置统计数据（这里使用模拟数据，实际项目中应该从API获取）
        cameraCount.value = stats?.camera_count || 8
        alertCount.value = stats?.unresolved_alerts || 12
        vehicleCount.value = stats?.today_vehicles || 1245
        violationCount.value = stats?.today_violations || 78
        
        // 获取最近告警数据
        const alerts = await api.alerts.getAlerts({ limit: 5, sort: 'timestamp', order: 'desc' })
        recentAlerts.value = alerts?.data || []
        
        // 如果没有数据，使用模拟数据
        if (recentAlerts.value.length === 0) {
          recentAlerts.value = [
            { id: 'AL-20240615-001', camera_name: '摄像头1', violation_type: '闯红灯', timestamp: '2024-06-15T14:32:15', status: 'unresolved' },
            { id: 'AL-20240615-002', camera_name: '摄像头3', violation_type: '超速', timestamp: '2024-06-15T13:45:30', status: 'unresolved' },
            { id: 'AL-20240615-003', camera_name: '摄像头2', violation_type: '违规停车', timestamp: '2024-06-15T12:10:45', status: 'confirmed' },
            { id: 'AL-20240615-004', camera_name: '摄像头5', violation_type: '逆行', timestamp: '2024-06-15T11:22:00', status: 'unresolved' },
            { id: 'AL-20240615-005', camera_name: '摄像头4', violation_type: '违规变道', timestamp: '2024-06-15T10:55:15', status: 'resolved' }
          ]
        }
        
      } catch (error) {
        console.error('获取仪表板数据失败:', error)
        // 使用模拟数据作为备用
        setMockData()
      } finally {
        loading.value = false
        await nextTick()
        initializeCharts()
      }
    }
    
    // 设置模拟数据
    const setMockData = () => {
      cameraCount.value = 8
      alertCount.value = 12
      vehicleCount.value = 1245
      violationCount.value = 78
      
      recentAlerts.value = [
        { id: 'AL-20240615-001', camera_name: '摄像头1', violation_type: '闯红灯', timestamp: '2024-06-15T14:32:15', status: 'unresolved' },
        { id: 'AL-20240615-002', camera_name: '摄像头3', violation_type: '超速', timestamp: '2024-06-15T13:45:30', status: 'unresolved' },
        { id: 'AL-20240615-003', camera_name: '摄像头2', violation_type: '违规停车', timestamp: '2024-06-15T12:10:45', status: 'confirmed' },
        { id: 'AL-20240615-004', camera_name: '摄像头5', violation_type: '逆行', timestamp: '2024-06-15T11:22:00', status: 'unresolved' },
        { id: 'AL-20240615-005', camera_name: '摄像头4', violation_type: '违规变道', timestamp: '2024-06-15T10:55:15', status: 'resolved' }
      ]
    }
    
    // 初始化图表
    const initializeCharts = () => {
      if (alertTrendChart.value) {
        if (alertTrendInstance) {
          alertTrendInstance.dispose()
        }
        alertTrendInstance = echarts.init(alertTrendChart.value)
        renderAlertTrendChart()
      }
      
      if (violationTypeChart.value) {
        if (violationTypeInstance) {
          violationTypeInstance.dispose()
        }
        violationTypeInstance = echarts.init(violationTypeChart.value)
        renderViolationTypeChart()
      }
    }
    
    // 渲染告警趋势图
    const renderAlertTrendChart = () => {
      const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
      // 模拟数据
      const alertData = [3, 1, 0, 0, 1, 2, 5, 8, 12, 15, 18, 14, 10, 8, 12, 16, 14, 9, 6, 4, 2, 1, 0, 0]
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: {
            interval: 2
          }
        },
        yAxis: {
          type: 'value',
          name: '告警数量'
        },
        series: [{
          name: '告警数量',
          type: 'line',
          smooth: true,
          data: alertData,
          areaStyle: {
            opacity: 0.3
          },
          itemStyle: {
            color: '#f56c6c'
          },
          lineStyle: {
            width: 3
          }
        }]
      }
      
      alertTrendInstance.setOption(option)
    }
    
    // 渲染违规类型分布图
    const renderViolationTypeChart = () => {
      // 模拟数据
      const data = [
        { value: 35, name: '闯红灯' },
        { value: 25, name: '超速' },
        { value: 15, name: '违规停车' },
        { value: 10, name: '逆行' },
        { value: 15, name: '其他违规' }
      ]
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: data.map(item => item.name)
        },
        series: [{
          name: '违规类型',
          type: 'pie',
          radius: '50%',
          center: ['60%', '50%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      violationTypeInstance.setOption(option)
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'unresolved': 'danger',
        'confirmed': 'warning',
        'resolved': 'success'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'unresolved': '未处理',
        'confirmed': '已确认',
        'resolved': '已解决'
      }
      return statusMap[status] || '未知'
    }
    
    // 查看告警详情
    const viewAlertDetail = (alertId) => {
      router.push(`/alerts/detail/${alertId}`)
    }
    
    // 页面挂载时初始化
    onMounted(() => {
      initializeData()
      
      // 监听窗口大小变化，调整图表
      window.addEventListener('resize', () => {
        alertTrendInstance?.resize()
        violationTypeInstance?.resize()
      })
    })
    
    return {
      loading,
      cameraCount,
      alertCount,
      vehicleCount,
      violationCount,
      recentAlerts,
      alertTrendChart,
      violationTypeChart,
      formatDateTime,
      getStatusType,
      getStatusText,
      viewAlertDetail
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding-bottom: 20px;
}

.page-card {
  margin-bottom: 20px;
}

.page-header {
  font-size: 16px;
  font-weight: 600;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-card.success {
  border-left: 4px solid #67c23a;
}

.stat-card.warning {
  border-left: 4px solid #e6a23c;
}

.stat-card.primary {
  border-left: 4px solid #409eff;
}

.stat-card.danger {
  border-left: 4px solid #f56c6c;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  margin-right: 16px;
}

.icon-large {
  font-size: 32px;
  opacity: 0.8;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 300px;
}

.chart-header {
  font-size: 14px;
  font-weight: 500;
}

.chart-container {
  height: 250px;
}

.chart-loading {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-content {
  width: 100%;
  height: 100%;
}

.alerts-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
}
</style>